
(function(window, undefined, $) {
	$(document).ready(function() {
		//$("#hRootID").val();
		pageDefault();
		//showHideDiv(false, false, false, false, false, false, false, false, false);
		
		//菜单内容radio切换
		$('input[name=type]').click(function(){
			
			switchType(this.value);
			
			if(this.value == '1'){
				switchMsgType($('.bianjinav li[msgType=text]'));
			} else if(this.value == '2'){
				$("#myForm").find("input[id='msgType']").val('');
				$("#myForm").find("textarea[id='content']").val('');
				$("#myForm").find("input[id='mediaId']").val('');
				$("#myForm").find("input[id='imageMediaId']").val('');
				$("#myForm").find("input[id='newsMediaId']").val('');
			}
		});
		
		$('.bianjinav li').click(function(){
			var _this = $(this);
			switchMsgType(_this);
		});
		
		var _submiting1 = false;
		$('#myForm').validator({
			rules : {},
			fields : {
				'#name' : 'required'
			},
			valid : function(form) {
				if (_submiting1) {

					return;
				}
				_submiting1 = true;

				FormSubmit(form, function(response) {
					_showInfoMessage("保存成功。", 'success');
					//options.goBack();
					$('#menuName'+response.data.id).text(response.data.name);
					
				});
				_submiting1 = false;
			}
		});

		$('#btnSave').click(function() {
			
			$('#myForm').submit();
			return false;
		});


		$('#fileIcon').change(function() {
			fileUpload(this);
		});
		$('#btnSelectNews').click(function() {

			$('#showNewsModal').modal('show');
			getMaterial(1);
		});
		$('#btnSaveNews').click(function() {

			var selectedItem = $('#newsContent').find('input[type=radio]:checked');
			if (selectedItem.length == 0) {
				_showInfoMessage('请选择一个图文素材。', 'error');
				return;
			}

			$('#newsMediaId').val(selectedItem.val());
			$('#mediaId').val(selectedItem.val());

			$('#showNewsModal').modal('hide');
		});
	});
	
	function switchMsgType(sender){
		sender.addClass('selected').siblings().removeClass('selected');
		
		var msgType = sender.attr('msgType');
		
		$('#'+ msgType + 'Container').show().siblings().hide();
		
		$('#msgType').val(msgType);
	}
	function switchType(v){
		
		if(v == '1'){
			$('#msgContainer').show();
			$('#urlContainer').hide();
			
			
		} else if(v =='2'){
			$('#msgContainer').hide();
			$('#urlContainer').show();
		}
	}
	var rootID = 0;
	function pageDefault() {
		// 同步读取左边菜单
		$.ajax({
			type : "post",
			async : false,
			url : options.getMenuList,
			success : function(response) {
				var menus = response.data;
				// 先生成一级菜单的DOM
				for (var i = 0; i < menus.length; i++) {
					if (menus[i].parentId == 0) {
						$("#menu").append(getH3AndUl(menus[i].id, menus[i].name));
					}
					$("#menu h3:eq(0)").css("border-top", "none");
				}
				// 再生成二级菜单的DOM
				for (var i = 0; i < menus.length; i++) {
					if (menus[i].parentId != 0) {
						$("#menu h3[menuid='" + menus[i].parentId+ "']").next("ul").append(getLi(menus[i].id, menus[i].name));
					}
				}
				
				//默认显示一个可编辑的菜单
				if(menus && menus.length > 0){
					showEditor(menus[0]);
				}
				
			}
		});
	}
	
	addup = function(level, id, sender) {
		if (level == 1) {
			if ($("#menu h3").length > 2) {
				_showInfoMessage("您最多只能添加3个菜单", 'error');
			} else {
				addMenu(rootID, level, sender);
			}
		}

		else if (id && level == 2) {
			if ($("#menu h3[menuid='" + id + "']").next("ul").find("li").length > 4) {
				_showInfoMessage("您最多只能添加5个菜单", 'error');
			} else {
				addMenu(id, level, sender);
			}
		}
	}

	// AJAX请求与数据库交互添加一个菜单
	var newMenuCount = 1;
	function addMenu(parentID, level, sender) {
		var menuName = (parentID==0?'':'子') + '菜单名称';
		
		$.ajax({
			url : options.saveMenuInfo,
			type : 'post',
			data : {
				id: 0,
				name : menuName,
				parentId : parentID,
				type : '1',
				msgType: 'text'
			},
			success : function(response) {
				var menuId = response.data.id;
				if (level == 1) {
					$("#menu").append(getH3AndUl(menuId, menuName));
					$("#menu h3:eq(0)").css("border-top", "none");
				} else if (level == 2) {
					$("#menu h3[menuid='" + parentID + "']").next("ul").append(
							getLi(menuId, menuName));
				}
				
				showEditor(response.data);
			},
			complete: function(){
				
			}
		});
		
		 
	}

	getMaterial = function(pageIndex) {
		$.ajax({
			url : 'getMaterial',
			type : 'post',
			data : {
				pageIndex : pageIndex
			},
			success : function(response) {

				var _html = '';
				if (response.total_count > 0) {
					$('#item_total').text(response.total_count);
					for (var i = 0; i < response.item.length; i++) {

						var item = response.item[i];
						console.log(item);
						_html += '<tr>';
						var firstOne = item.content.news_item[0];
						_html += '<td>' + firstOne.title + '</td>';
						_html += '<td><img style="width:50px;height:30px;" src="'
								+ firstOne.thumb_url + '" /></td>';
						_html += '<td>' + firstOne.digest + '</td>';
						_html += '<td><input type="radio" value="' + item.media_id
								+ '" name="optionsRadios"></td>';

						_html += '</tr>';
					}
				}

				$('#newsContent').html(_html);
			},
			error : function(result) {
				_showInfoMessage("操作失败。", 'error');
			}
		});
	}
	fileUpload = function(sender) {
		$.ajaxFileUpload({
			url : 'fileUpload', // 用于文件上传的服务器端请求地址
			type : 'post',
			data : {
				"folder" : "app/",
				"extension" : ".png"
			}, // JSON格式
			secureuri : false, // 一般设置为false
			fileElementId : 'fileIcon', // 文件上传空间的id属性 <input type="file" id="file"
			// name="file" />
			dataType : 'json', // 返回值类型 一般设置为json
			global : true,
			success : function(response, status) { // 服务器成功响应处理函数

				if (response.media_id) {
					$('#imageMediaId').val(response.media_id);
					$('#mediaId').val(response.media_id);
				}
			},
			error : function(data, status, e) {// 服务器响应失败处理函数
				_showInfoMessage(e, 'error');
			}
		});
	}
	publishMenu = function() {
		if(!confirm('确定发布到线上吗？')){
			return;
		}
		$.post(options.publishMenuUrl, {
			
		}, function(ret) {

			if (ret.errorCode == '0') {
				_showInfoMessage("发布成功。", 'success');
			} else {
				_showInfoMessage("发布失败。", 'error');
			}
			
		}, "json");
	};
	deleteaway = function(level, id) {
		if(!confirm('确定删除吗？')){
			return;
		}
		$.post(options.deleteMenuInfoUrl, {
			id : id
		}, function(ret) {
			if (ret.errorCode == '0') {
				if (id && level == 1) {
					// 删 h3 和 ul
					$("#menu h3[menuid='" + id + "']").next("ul").remove();
					$("#menu h3[menuid='" + id + "']").remove();
				} else if (id && level == 2) {
					// 删 li
					$("#menu ul li[menuid='" + id + "']").remove();
				}

				_showInfoMessage("删除成功。", 'success');
			} else {
				_showInfoMessage("删除失败：父级菜单不能删除。", 'error');
			}
		}, "json");
	};
	edit = function(id) {

		$.ajax({
			type : "post",
			async : false,
			url : options.getMenuInfo,
			data : {
				id : id
			},
			success : function(ret) {
				if (ret.errorCode == '0') {
					showEditor(ret.data);
				}
			}
		});
	}
	showEditor = function(data){
		
		$("#myForm").find("input[id='name']").val(data.name);
		$("#myForm").find("input[id='id']").val(data.id);
		var _type = data.type;
		$('input[name=type][value='+_type+']').prop('checked', true);
		switchType(_type);
		
		var _url = data.url;
		var _content = data.content;
		var _mediaId = data.mediaId;
		var _imageMediaId = '';
		var _newsMediaId = '';
		var _msgType = data.msgType;
		if(_type == 1) {	//发送消息
			_url = '';
			if(_msgType == 'text'){
				_mediaId = '';
			} else if(_msgType == 'image'){
				_content = '';
				_imageMediaId = _mediaId;
			} else if(_msgType == 'news'){
				_content = '';
				_newsMediaId = _mediaId;
			}
			
		} else if(_type == 2) {	//跳转
			_content = '';
			_mediaId = '';
			_msgType = '';
		}

		$("#myForm").find("input[id='url']").val(_url);		

		$("#myForm").find("textarea[id='content']").val(_content);

		$("#myForm").find("input[id='msgType']").val(_msgType);
		if(_msgType!=''){
			switchMsgType($('.bianjinav li[msgType='+_msgType+']'));
		}
		
				
		$("#myForm").find("input[id='mediaId']").val(_mediaId);
		$("#myForm").find("input[id='imageMediaId']").val(_imageMediaId);
		$("#myForm").find("input[id='newsMediaId']").val(_newsMediaId);
		
		setAction(data.id);
	}
	
	setAction = function(id) {
		$("#menu li").removeClass("curzi");
		$("#menu h3").removeClass("curzi");
		$("#menu [menuid='" + id + "']").addClass("curzi");

		/*if (res.errorCode == '0') {
			var menu = res.data;
			domInitialize(menu);

			if (menu.Type == null) { // 没有设置过 默认界面
				showHideDiv(true, false, false, false, false, false, false,
						false, false);
			} else {
				if (menu.type == 0) {
					showHideDiv(false, true, true, true, false, false, false,
							false, false);
				} else if (menu.type == 1) {
					// domInitialize会在AJAX执行后showHideDiv
				} else if (menu.type == 3) {
					showHideDiv(false, false, false, false, false, false, true,
							true, false);
				} else {
				}
			}
		}*/
		
	}
	
	close = function() {
		$("#tishi").css("display", "none");
		$("#tishibg").css("display", "none");
	}

	tuoye = function() {
		$(".zidingyiTItle").find("bdo").hide();
		$(".zidingyiTItle").find("i").fadeIn();
		sortall();
	}

	notuoye = function() {
		$(".zidingyiTItle").find("bdo").fadeIn();
		$(".zidingyiTItle").find("i").hide();
		baocun();

		$("#menu").empty();
		pageDefault();
	}

	complete = function() {
		var list0 = [];
		$("#menu ul").each(function() {
			var list1 = [];
			$(this).find("li").each(function() {
				var li = $(this);
				var menu = {
					"id" : parseInt(li.attr("menuid")),
					"name" : li.text()
				};
				list1.push(menu);
			});
			list0.push({
				children : list1
			});
		});

		var obj = {
			menuJSON : $.toJSON({
				menus : list0
			})
		};

		$.ajax({
			type : "post",
			async : false,
			url : options.saveMenuOrderUrl,
			data : obj,
			success : function(ret) {
				notuoye();
			}
		});
	}

	

	setNewClick = function() {
		$("#divClick #watch #text p").text("");
		$("#divClick #edit").find("textarea[name='txtContent']").val("");
		gbcount(500);
		showHideDiv(false, true, false, false, false, true, false, false, false);
	}

	editClick = function() {
		var pText = $("#divClick #watch #text p").text();
		$("#divClick").find("textarea[name='txtContent']").val(pText);
		gbcount(500);
		showHideDiv(false, true, false, false, false, true, false, false, false);
	}

	saveClick = function() {
		var id = $(".zidingyicon").find("input[type='hidden'][name='hfID']")
				.val();
		var content = $.trim($("#divClick").find("textarea[name='txtContent']")
				.val());
		if (content != "") {
			$.post(options.saveMenuUrl, {
				id : id,
				type : 0,
				typeArg : content
			}, function(res) {
				if (res.status == 0) {
					var menu = res.data;
					domInitialize(menu);
					showHideDiv(false, true, true, true, false, false, false,
							false, false);
				}
			}, "json");
		} else {
			_showInfoMessage("请输入内容。", 'error');
		}
	}

	returnClick = function() {
		var type = $(".zidingyicon")
				.find("input[type='hidden'][name='hfType']").val();
		if (type == "") {
			showHideDiv(true, false, false, false, false, false, false, false,
					false);
		} else {
			if (type == "0") {
				showHideDiv(false, true, true, true, false, false, false,
						false, false);
			} else if (type == "1") {
				showHideDiv(false, true, true, false, true, false, false,
						false, false);
			}
		}
	}

	setNewView = function() {
		$("#divView #links p").text("");
		$("#divView #nolinks input[type='text'][name='txtUrl']").val("");
		showHideDiv(false, false, false, false, false, false, true, false, true);
	}

	editView = function() {
		var pText = $("#divView #links p").text();
		$("#divView #nolinks input[type='text'][name='txtUrl']").val(pText);
		showHideDiv(false, false, false, false, false, false, true, false, true);
	};

	saveView = function() {
		var id = $(".zidingyicon").find("input[type='hidden'][name='hfID']")
				.val();
		var url = $("#divView").find("input[type='text'][name='txtUrl']").val();
		// if (isURL(url)) {
		$.post(options.saveMenuUrl, {
			id : id,
			type : 3,
			typeArg : url
		}, function(res) {
			if (res.status == 0) {
				var menu = res.data;
				domInitialize(menu);
				showHideDiv(false, false, false, false, false, false, true,
						true, false);
			}
		}, "json");
		// }
		// else {
		// alert("请输入一个有效url。");
		// }
	}

	returnView = function() {
		if ($(".zidingyicon").find("input[type='hidden'][name='hfType']").val() == "") {
			showHideDiv(true, false, false, false, false, false, false, false,
					false);
		} else {
			showHideDiv(false, false, false, false, false, false, true, true,
					false);
		}
	}

	function getByteLen(val) {
		var len = 0;
		for (var i = 0; i < val.length; i++) {
			if (val[i].match(/[^\x00-\xff]/ig) != null) // 全角
				len += 2;
			else
				len += 1;
		}
		return len;
	}

	gbcount = function(num) {
		var txtlen = getByteLen(document.getElementById('content').value);
		var curlen = num - txtlen;
		if (curlen >= 0) {
			$("#area2").next(".bianjitext")
					.html("还可以输入" + curlen + "个字符，中文占2个");
		} else {
			$("#area2").next(".bianjitext").html(
					"已超出<strong>" + (-curlen) + "</strong>字符");
		}
	}

	function isURL(url) {
		var strRegex = "^((https|http|ftp|rtsp|mms)://)?[a-z0-9A-Z]{3}\.[a-z0-9A-Z][a-z0-9A-Z]{0,61}?[a-z0-9A-Z]\.com|net|cn|cc (:s[0-9]{1-4})?/$";
		var re = new RegExp(strRegex);
		if (re.test(url)) {
			return true;
		} else {
			return false;
		}
	}

	// 拖拽模式
	function sortall() {
		var quanli = $("#menu li");
		for (var b = 0; b < quanli.length; b++) {
			$(quanli[b]).find("dd").show();
		}
		$('#menu').removeClass("zidingTT2");
		$('#menu ul').sortable().bind('sortupdate');
	}

	// 非拖拽模式
	function baocun() {
		var quanli = $("#menu li");
		for (var c = 0; c < quanli.length; c++) {
			$(quanli[c]).find("dd").hide();
		}
		$('#menu').addClass("zidingTT2");
	}

	changeName = function() {
		$("#frmChangeName").submit();
	};

	$('#frmChangeName').validator(
			{
				rules : {},
				fields : {
					Name : "required"
				},
				valid : function(form) {
					FormSubmit(form, function(res) {
						if (res.status == 0) {
							// 左边更新DOM元素
							if (res.data.Depth == 1) {
								// $("#menu h3[menuid='" + res.data.ID +
								// "']").text(res.data.Name);
								$("#menu h3[menuid='" + res.data.ID + "']")
										.html(
												getH3ExceptTag(res.data.ID,
														res.data.Name));
							} else if (res.data.Depth == 2) {
								$("#menu li[menuid='" + res.data.ID + "']")
										.html(
												getLiExceptTag(res.data.ID,
														res.data.Name));
							}
						}
						close();
					})
				}
			});

	function getH3AndUl(id, name) {
		// 生成 h3 和 ul
		return '<h3 menuid='
				+ id
				+ '><span><a href="javascript:addup(2,'
				+ id
				+ ', this);" class="jiahao2"></a> <a href="javascript:edit('
				+ id
				+ ');" class="editicon"></a> <bdo><a href="javascript:deleteaway(1,'
				+ id + ');" class="delicon"></a></bdo></span><em id="menuName'+id+'">' + name
				+ '</em></h3><ul></ul>';
	}

	function getH3ExceptTag(id, name) {
		return '<span><a href="javascript:addup(2,'
				+ id
				+ ', this);" class="jiahao2"></a> <a href="javascript:edit('
				+ id
				+ ');" class="editicon"></a> <bdo><a href="javascript:deleteaway(1,'
				+ id + ');" class="delicon"></a></bdo></span>' + name;
	}

	function getLi(id, name) {
		// 生成 li
		return '<li menuid='
				+ id
				+ '><span><a href="javascript:edit('
				+ id
				+ ');" class="editicon"></a> <bdo><a href="javascript:deleteaway(2,'
				+ id
				+ ')" class="delicon"></a></bdo></span><dd><a href="javascript:void(0)" class="tuoicon"></a></dd><em id="menuName'+id+'">'
				+ name + '</em></li>';
	}

	function getLiExceptTag(id, name) {
		return '<span><a href="javascript:edit('
				+ id
				+ ');" class="editicon"></a> <bdo><a href="javascript:deleteaway(2,'
				+ id
				+ ')" class="delicon"></a></bdo></span><dd><a href="javascript:void(0)" class="tuoicon"></a></dd>'
				+ name;
	}

	publish = function() {
		$.ajax({
			type : "POST",
			url : options.publishToWechatUrl,
			dataType : "json",
			success : function(ret) {
				if (ret.status == 0) {
					_showInfoMessage("发布成功,创建自定义菜单后,由于微信客户端缓存，需要24小时微信客户端才会展现出来。", 'success');
					 
				} else {
					_showInfoMessage("发布失败，errcode:" + ret.status + ",errmsg:"
							+ ret.message, 'error');
				}
			},
			error : function(d, c, e) {
				_showInfoMessage(d + " " + c + " " + e, 'error');
			}
		});
		// }
	}
})(window, undefined, jQuery);

// boolDefault
// boolClick
// boolWatch
// boolWatchText
// boolWatchGraphic
// boolView
// boolLinks
// boolNolinks
function showHideDiv(boolDefault, boolClick, boolWatch, boolWatchText,
		boolWatchGraphic, boolEdit, boolView, boolLinks, boolNolinks) {
	$("#divDefault").hide();
//	$("#divClick").hide();
//	$("#divClick #watch").hide();
//	$("#divClick #watch #text").hide();
//	$("#divClick #watch #graphic").hide();
//	$("#divClick #edit").hide();
	$("#divView").hide();
	$("#divView #links").hide();
	$("#divView #nolinks").hide();

	if (boolDefault) {
		$("#divDefault").fadeIn();
	}

	if (boolClick) {
		$("#divClick").fadeIn();
		if (boolWatch) {
			$("#divClick #watch").fadeIn();

			if (boolWatchText) {
				$("#divClick #watch #text").fadeIn();
			}
			if (boolWatchGraphic) {
				$("#divClick #watch #graphic").fadeIn();
			}
		}
		if (boolEdit) {
			$("#divClick #edit").fadeIn();
		}
	}

	if (boolView) {
		$("#divView").fadeIn();
		if (boolLinks) {
			$("#divView #links").fadeIn();
		}
		if (boolNolinks) {
			$("#divView #nolinks").fadeIn();
		}
	}
}

function domInitialize(menu) {
	$(".zidingyicon").find("input[type='hidden'][name='hfID']").val(menu.id);
	$(".zidingyicon").find("input[type='hidden'][name='hfType']")
			.val(menu.type);
	$("#divClick #watch #text p").text("");
	$("#divClick #edit").find("textarea[name='txtContent']").val("");
	$("#divClick #watch #graphic .tuwen").empty();
	$("#divView #links p").text("");
	$("#divView #nolinks input[type='text'][name='txtUrl']").val("");

	if (menu.Type == "0") {
		$("#divClick #watch #text p").text('内容是');
		gbcount(500);
	}

	else if (menu.Type == "1") {
		showGraphic(menu.Graphic_ID);
	}

	else if (menu.Type == "3") {
		$("#divView #links p").text(menu.Url);
	} else {

	}
}